package com.vdimitr.happycube.puzzle.piece.construction;

import com.vdimitr.happycube.puzzle.matrix.PuzzlePieceMatrixTransformer;
import com.vdimitr.happycube.puzzle.matrix.bycolor.PuzzlePieceMatrixRetriever;
import com.vdimitr.happycube.puzzle.piece.PuzzlePiece;

/**
 * This class is responsible for loading a puzzle piece with its respective
 * matrix representation and adjusting it to the puzzle piece's state (flip and
 * rotation).
 * 
 * @author vasileios.dimitriadis
 * 
 */
public class PuzzlePieceMatrixLoader {

	/**
	 * Knows how to locate the matrix representation of a puzzle piece
	 */
	private PuzzlePieceMatrixRetriever retriever = new PuzzlePieceMatrixRetriever();

	/**
	 * Knows how to flip and rotate the matrix representation of a puzzle piece
	 * to match its state
	 */
	private PuzzlePieceMatrixTransformer transformer = new PuzzlePieceMatrixTransformer();

	/**
	 * Find the matrix corresponding to the input puzzle piece, adjust it to
	 * match the puzzle piece's flip and rotation and set it
	 * 
	 * @param puzzlePiece
	 *            a puzzle piece with only its matrix missing
	 */
	public void loadPuzzlePieceMatrix(PuzzlePiece puzzlePiece) {
		setPuzzlePieceMatrix(puzzlePiece);
		adjustPuzzlePieceMatrixToMatchState(puzzlePiece);
	}

	/**
	 * Rotate and flip matrix to match puzzle piece state
	 * 
	 * @param puzzlePiece
	 *            the puzzle piece with its matrix
	 */
	private void adjustPuzzlePieceMatrixToMatchState(PuzzlePiece puzzlePiece) {
		transformer.adjustPuzzlePieceMatrix(puzzlePiece);
	}

	/**
	 * Locates and sets the puzzle piece's matrix representation
	 * 
	 * @param puzzlePiece
	 *            the puzzle piece to set its matrix
	 */
	private void setPuzzlePieceMatrix(PuzzlePiece puzzlePiece) {
		int[][] puzzlePieceMatrix = retriever.getMatrix(puzzlePiece.getColor(),
				puzzlePiece.getPuzzlePieceNumber());
		puzzlePiece.setMatrix(puzzlePieceMatrix);
	}
}
